<?php
/**
 * Created by Boume.
 * Date: 4/29 0029
 * Time: 23:30
 */
namespace app\admin\controller;

use app\admin\model\LoginLog;
use think\captcha\Captcha;
use think\Controller;
use tool\Crypt;

class Passport extends Controller
{
    public function login()
    {
        if ($this->request->isPost()) {
            $crypt = new Crypt();
            $captcha = new Captcha();
            if (!$captcha->check(input('vercode'))) {
                $this->error('验证码错误');
            }
            $admin = \app\admin\model\Admin::where('username', input('username'))->find();
            if(empty($admin)) $this->error('用户不存在');
            if($admin->password!=$crypt->encrypt(input('password'))) $this->error('密码错误');

            //判断用户组是否锁定
            if($admin->Role->lock==1) $this->error('角色组被锁定：' . $admin->Role->lock_msg);
            if($admin->lock==1) $this->error('用户被锁定：' . $admin->lock_msg);

            //获取用户IP并且入库
            $login_log = new LoginLog();
            $login_log->save([
                'admin_id' => $admin->id,
                'time' => time(),
                'ip' => $this->request->ip(),
            ]);

            session('U', [
                'id' => $admin->id,
                'name' => $admin->name,
                'username' => $admin->username,
                'addtime' => $admin->addtime,
                'edit_password_time' => $admin->getData('edit_password_time'),
                'mobile' => $admin->mobile,
                'role_id' => $admin->Role->id,
                'role_name' => $admin->Role->role_name,
            ]);
            return json([
                'code' => 1,
                'msg' => '登录成功',
                'url' => url('index/index'),
            ]);
        } else {
            if(session('?U')) $this->redirect('index/index');
            return $this->fetch();
        }
    }

    public function logout()
    {
        session('U', null);
        $this->redirect('passport/login');
    }
}